package com.tz.online.user.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.tz.online.entity.Address;
import com.tz.online.user.dao.IAddressDao;
import com.tz.online.util.HibernateCallback;
import com.tz.online.util.HibernateTemplate;

public class AddressDaoImpl implements IAddressDao {

	private HibernateTemplate template = new HibernateTemplate();
	
	@Override
	public void save(Address a) {
		//
		template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.save(a);
				return null;
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Address> findByUserId(Long userId) {
		//
		return (List<Address>) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.createQuery("from Address as a where a.user.id = ?")
						.setLong(0, userId)
						.list();
			}
		});
	}

	@Override
	public void delete(Address a) {
		//
		template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.delete(a);
				return null;
			}
		});
	}

	@Override
	public Address findById(Long id) {
		return (Address) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.get(Address.class, id);
			}
		});
	}

	@Override
	public void update(Address a) {
		//
		template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.update(a);
				return null;
			}
		});

	}

}
